<template>
  <div class="form-preview">
    <el-form 
      ref="previewFormRef"
      :model="formData" 
      :rules="formRules"
      label-width="120px" 
      size="large"
    >
      <el-form-item 
        v-for="field in (fields || [])" 
        :key="field.id"
        :label="field.label"
        :prop="field.name"
        :required="field.required"
      >
        <!-- 单行文本 -->
        <el-input 
          v-if="field.type === 'text'"
          v-model="formData[field.name]"
          :placeholder="field.placeholder"
          clearable
        />
        
        <!-- 多行文本 -->
        <el-input 
          v-else-if="field.type === 'textarea'"
          v-model="formData[field.name]"
          type="textarea"
          :placeholder="field.placeholder"
          :rows="3"
          resize="vertical"
        />
        
        <!-- 数字输入 -->
        <el-input-number 
          v-else-if="field.type === 'number'"
          v-model="formData[field.name]"
          :placeholder="field.placeholder"
          :min="0"
          style="width: 100%"
        />
        
        <!-- 下拉选择 -->
        <el-select 
          v-else-if="field.type === 'select'"
          v-model="formData[field.name]"
          :placeholder="field.placeholder"
          clearable
          style="width: 100%"
        >
          <el-option 
            v-for="option in field.options" 
            :key="option.value"
            :label="option.label" 
            :value="option.value"
          />
        </el-select>
        
        <!-- 单选按钮 -->
        <el-radio-group 
          v-else-if="field.type === 'radio'"
          v-model="formData[field.name]"
        >
          <el-radio 
            v-for="option in field.options" 
            :key="option.value"
            :label="option.value"
          >
            {{ option.label }}
          </el-radio>
        </el-radio-group>
        
        <!-- 多选框 -->
        <el-checkbox-group 
          v-else-if="field.type === 'checkbox'"
          v-model="formData[field.name]"
        >
          <el-checkbox 
            v-for="option in field.options" 
            :key="option.value"
            :value="option.value"
          >
            {{ option.label }}
          </el-checkbox>
        </el-checkbox-group>
        
        <!-- 日期选择 -->
        <el-date-picker 
          v-else-if="field.type === 'date'"
          v-model="formData[field.name]"
          type="date"
          :placeholder="field.placeholder"
          format="YYYY-MM-DD"
          style="width: 100%"
        />
        
        <!-- 日期时间选择 -->
        <el-date-picker 
          v-else-if="field.type === 'datetime'"
          v-model="formData[field.name]"
          type="datetime"
          :placeholder="field.placeholder"
          format="YYYY-MM-DD HH:mm:ss"
          style="width: 100%"
        />
        
        <!-- 开关 -->
        <el-switch 
          v-else-if="field.type === 'switch'"
          v-model="formData[field.name]"
        />
      </el-form-item>
    </el-form>
    
    <!-- 表单数据展示 -->
    <div class="form-data-display">
      <h4>当前表单数据：</h4>
      <pre>{{ JSON.stringify(formData, null, 2) }}</pre>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch, withDefaults } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import type { FormField } from '/@/components/FormDesigner/types/index'

// Props
interface Props {
  fields?: FormField[]
}

// Emits
interface Emits {
  (e: 'form-data-change', data: Record<string, any>): void
}

const props = withDefaults(defineProps<Props>(), {
  fields: () => []
})
const emit = defineEmits<Emits>()

// Refs
const previewFormRef = ref<FormInstance>()

// 响应式数据
const formData = reactive<Record<string, any>>({})

// 计算属性
const formRules = computed<FormRules>(() => {
  const rules: FormRules = {}
  
  if (props.fields && Array.isArray(props.fields)) {
    props.fields.forEach(field => {
      if (field.required) {
        rules[field.name] = [
          { required: true, message: `请输入${field.label}`, trigger: 'blur' }
        ]
      }
    })
  }
  
  return rules
})

// 方法
const initFormData = () => {
  // 清空现有数据
  Object.keys(formData).forEach(key => {
    delete formData[key]
  })
  
  // 初始化表单数据
  if (props.fields && Array.isArray(props.fields)) {
    props.fields.forEach(field => {
    let defaultValue = field.defaultValue || ''
    
    // 根据字段类型设置默认值
    switch (field.type) {
      case 'number':
        defaultValue = field.defaultValue ? Number(field.defaultValue) : 0
        break
      case 'checkbox':
        defaultValue = []
        break
      case 'switch':
        defaultValue = false
        break
      case 'date':
      case 'datetime':
        defaultValue = null
        break
      default:
        defaultValue = field.defaultValue || ''
    }
    
      formData[field.name] = defaultValue
    })
  }
}



// 表单验证方法
const validate = async (): Promise<boolean> => {
  if (!previewFormRef.value) {
    return false
  }
  
  try {
    await previewFormRef.value.validate()
    return true
  } catch (error) {
    return false
  }
}

// 重置表单
const resetForm = () => {
  if (previewFormRef.value) {
    previewFormRef.value.resetFields()
  }
  initFormData()
}

// 获取表单数据
const getFormData = () => {
  return { ...formData }
}

// 监听器
watch(() => props.fields, () => {
  initFormData()
}, { immediate: true, deep: true })

// 监听表单数据变化，触发事件
watch(formData, (newData) => {
  emit('form-data-change', { ...newData })
}, { deep: true })

// 暴露方法给父组件
defineExpose({
  validate,
  resetForm,
  getFormData
})
</script>

<style scoped>
.form-preview {
  padding: 16px;
}



.form-data-display {
  margin-top: 24px;
  padding: 16px;
  background: #f5f7fa;
  border-radius: 4px;
}

.form-data-display h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #303133;
}

.form-data-display pre {
  margin: 0;
  font-size: 12px;
  color: #606266;
  white-space: pre-wrap;
  word-break: break-word;
}
</style>